package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.LoginDto;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @Author mr.fu
 * @Date 2025/1/11 21:44
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult login(LoginDto dto) {

        Map<String, Object> map = new HashMap<>();
        // 1.判断是否用户登录
        if (!dto.getPassword().equals("") && !dto.getPhone().equals("")) {
            // 2.根据手机号查询数据库是否存在
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(dto.getPhone() != null, ApUser::getPhone, dto.getPhone()));
            if (apUser == null) {
                // 用户不存在
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "用户不存在哦~");
            }
            // 3.存在进行密码校验
            //获取salt
            String salt = apUser.getSalt();
            //获取密码
            String password = dto.getPassword();
            String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (pwd.equals(apUser.getPassword())) {
                // 4.一致的话返回前台需要的信息
                apUser.setPassword("");
                apUser.setSalt("");
                map.put("user", apUser);
                String token = AppJwtUtil.getToken(apUser.getId().longValue());
                map.put("token", token);
                return ResponseResult.okResult(map);
            } else {
                // 密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误哦~");
            }
        }
        // 5.游客登录,直接返回token,id=0
        map.put("token", AppJwtUtil.getToken(0L));
        return ResponseResult.okResult(map);
    }
}
